﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CodeBuilder.Code;

namespace CodeBuilder
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void btn_load_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txt_conn.Text))
            {
                MessageBox.Show("请输入数据库连接");
            }
            else
            {
                try
                {
                    var structure = new SqlStructure(txt_conn.Text);
                    var list = new List<object>();
                    foreach (var item in structure.Tables)
                    {
                        list.Add(new {Value=item,Name=item + "(表)" });
                    }
                    foreach (var item in structure.Views)
                    {
                        list.Add(new { Value = item, Name = item+"(视图)" });
                    }
                    cbb_table.DataSource = list;
                    cbb_table.DisplayMember = "Name";
                }
                catch (Exception ex)
                {
                    MessageBox.Show("请检查连接是否正常");
                }

            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            
            dynamic obj = cbb_table.SelectedItem;
            if (obj == null || string.IsNullOrEmpty(obj.Value))
            {
                MessageBox.Show("请选择表或视图");
                return;
            }
            else if (string.IsNullOrEmpty(txt_sln.Text))
            {
                MessageBox.Show("请选择sln文件");
                return;
            }
            else if (string.IsNullOrEmpty(txt_controller.Text))
            {
                MessageBox.Show("请输入controller");
                return;
            }
            try
            {
                new BuildHelper(txt_conn.Text, txt_sln.Text, txt_controller.Text, obj.Value).Process();
                MessageBox.Show("生成成功");
            }
            catch (Exception ex)
            {
                MessageBox.Show("生成失败：" + ex);
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            var dlg = new OpenFileDialog();
            dlg.Filter = "*.sln|*.sln";
            dlg.DefaultExt = ".sln";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                txt_sln.Text = dlg.FileName;
            }
        }

        private void cbb_table_SelectedIndexChanged(object sender, EventArgs e)
        {
            dynamic obj = cbb_table.SelectedItem;
            if (obj != null && !string.IsNullOrEmpty(obj.Value))
            {
                txt_controller.Text = obj.Value;
            }
        }
    }
}
